import React from 'react';
import {inject, observer} from 'mobx-react';

import {Tabs, Button, Checkbox, Icon} from 'antd';
import {WeaTools, WeaScroll, WeaLocaleProvider} from 'ecCom';
import NodeItem from './NodeItem';
import * as mobx from 'mobx';
import forIn from 'lodash/forIn';
import concat from 'lodash/concat';
const TabPane = Tabs.TabPane;
const getLabel = WeaLocaleProvider.getLabel;

@observer
class NodeOperator extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            selectTabKey: '1',
            selectAll: false,
            selectedInfo: {},
            showAllUser:{isShowAll:false, users:[],nodeid:''}
        };
    }

    render() {
        const {selectTabKey = '1', selectAll = false} = this.state;
        const {nodeOperatorTitle = ''} = this.props;
        return (
            <div className="wea-req-node-operator">
                <div className="title">
                    <span>{nodeOperatorTitle.length > 0 ?nodeOperatorTitle : getLabel('84509',"选择节点参与人作为转发对象")}</span>
                </div>
                <div className="content">
                    <Tabs ecId={`${this && this.props && this.props.ecId || ''}_Tabs@fmzf56`} activeKey={selectTabKey} tabBarExtraContent={<Checkbox ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@h96n35`} checked={selectAll}
                                                                                 onChange={this.selectAll}>{getLabel(556,'全选')}</Checkbox>}
                          onChange={this.changeTab}>
                        {this.getTabPaneCom()}
                    </Tabs>
                </div>
                <div className="footer">
                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8ih8yd`} type="primary" onClick={this.btnOnClick}>{getLabel(83446,'确定')}</Button>
                </div>
            </div>
        )
    }

    getTabPaneCom() {
        const {allitems = [], submititems = [], unsubmititems = []} = this.props.wfForwardStore;
        const tabs = [{key: '1', title: getLabel(126831,'全部'), datas: mobx.toJS(allitems)},
            {key: '2', title: getLabel('32555',"未提交"), datas: mobx.toJS(unsubmititems)},
            {key: '3', title: getLabel('15176',"已提交"), datas: mobx.toJS(submititems)}];
        const nodata = (<div className="no-data">{getLabel('83781',"没有数据")}</div>);
        return tabs.map((tab) => {
            const {key, title, datas = []} = tab;
            return (
                <TabPane ecId={`${this && this.props && this.props.ecId || ''}_TabPane@ul7sy5@${key}`} tab={title} key={key}>
                    {datas.length > 0 ?
                        <WeaScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaScroll@lzxysz@${key}`} className="wea-scroll" typeClass="scrollbar-macosx">
                            <div className="node-table">
                                {this.getItemCom(datas,key)}
                            </div>
                        </WeaScroll>
                        :
                        nodata
                    }
                </TabPane>
            )
        })
    }

    getItemCom(items = [],tabKey) {
        const {selectedInfo = {},showAllUser = {},selectTabKey = '1'} = this.state;
        const {isShowAll = false} = showAllUser;
        if(selectTabKey !== tabKey) {
            return (<div></div>);
        }
        if(isShowAll) {
            const {nodeAllUsers = [],nodeid = ''}  = showAllUser;
            const nodeSelectedUsers = selectedInfo[nodeid]||[];
            return (<NodeItem ecId={`${this && this.props && this.props.ecId || ''}_NodeItem@w381uh`} item={showAllUser} nodeSelectedUsers={nodeSelectedUsers}
                      addOrRemoveSelectedUser={this.addOrRemoveSelectedUser}
                      showAllNodeUsers = {this.showAllNodeUsers}/>)
        } else {
            return items.map((item,ecindex) => {
                const {nodeid = ''} = item;
                const nodeSelectedUsers = selectedInfo[nodeid] || [];
                return (<NodeItem ecId={`${this && this.props && this.props.ecId || ''}_NodeItem@0jvswm@${ecindex}`} item={item} nodeSelectedUsers={nodeSelectedUsers}
                                  addOrRemoveSelectedUser={this.addOrRemoveSelectedUser}
                                  showAllNodeUsers = {this.showAllNodeUsers}
                                  updateSelectIds={this.updateSelectIds}/>)
            })
        }
    }

    btnOnClick = () =>  {
        const {handleShowNodeOperator, setOperatorIds} = this.props.wfForwardStore;
        const {selectedInfo = {}} = this.state;
        let selectedUsers = [];
        forIn(selectedInfo,(v = [],k)=>{
            selectedUsers =  concat(selectedUsers,v);
        });
        setOperatorIds({
            datas: selectedUsers,
            isAllUser: false
        });
        handleShowNodeOperator(false);
        this.setState({
            selectTabKey: '1',
            selectedInfo: {},
            selectAll: false,
            showAllUser:{}
        });
    }

    changeTab = (key)  => {
        this.setState({
            selectTabKey: key,
            selectAll: false,
            selectedInfo: {},
            showAllUser:{}
        });
    }

    selectAll = (e) =>  {
        if (e.target.checked) {
            let selectedInfo = {};
            const currentItemDatas = this.getCurrentItemDatas();
            currentItemDatas && currentItemDatas.map(o => {
                selectedInfo[o.nodeid] = o.users;
            });
            this.setState({
                selectedInfo,
                selectAll: true
            });
        } else {
            this.setState({
                selectedInfo: {},
                selectAll: false
            });
        }
    }

    updateSelectIds = (bool, nodeid)  => {
        let {selectedInfo = {}, selectTabKey} = this.state;
        let selectAll = false;
        if (bool) {
            const currentItemDatas = this.getCurrentItemDatas();
            currentItemDatas && currentItemDatas.map(o => {
                if (o.nodeid === nodeid) {
                    selectedInfo[o.nodeid] = o.users;
                }
            });
            selectAll = this.isSelectAll(currentItemDatas, selectedInfo);
        } else {
            delete selectedInfo[nodeid];
        }
        this.setState({
            selectedInfo,
            selectAll
        });
    }

    showAllNodeUsers = (d = {}) =>  {
        this.setState({showAllUser:d});
    }

    getCurrentItemDatas() {
        const {selectTabKey = '1'} = this.state;
        const {allitems = [], submititems = [], unsubmititems = []} = this.props.wfForwardStore;
        let currentItems = mobx.toJS(allitems);
        if (selectTabKey === '2') currentItems = mobx.toJS(unsubmititems);
        if (selectTabKey === '3') currentItems = mobx.toJS(submititems);
        return currentItems;
    }

    isSelectAll(currentItemDatas = {}, selectedInfo = []) {
        let allSelected = true;
        currentItemDatas.map((item) => {
            const nodeSelectedUsers = selectedInfo[item.nodeid] || [];
            if (nodeSelectedUsers.length == 0) allSelected = false;
        })
        return allSelected;
    }

    addOrRemoveSelectedUser = (operate, user = {}, item = {}) =>  {
        const {nodeid = '',users = []} = item;
        let {selectedInfo = {}, selectAll = false} = this.state;
        let nodeSelectedUsers = selectedInfo[nodeid] || [];
        if (operate === 'add') {
            nodeSelectedUsers.push(user);
        } else {
            nodeSelectedUsers = nodeSelectedUsers.filter((u) => u.id !== user.id);
        }
        if(nodeSelectedUsers.length !==  users.length) {
            selectAll = false;
        }
        if (nodeSelectedUsers.length === 0) {
            delete selectedInfo[nodeid];
            selectAll = false;
        } else {
            selectedInfo[nodeid] = nodeSelectedUsers;
        }
        this.setState({
            selectedInfo,
            selectAll
        });
    }
}

export default NodeOperator